import { useContext, useLayoutEffect, useState } from "react";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import settingIcon from "../images/Setting_line_light.svg";
import { IsTestingContext, datasetContext } from "./context";
import {
  getDatasetNameList,
  initTestParams,
  runTest,
  stopTest,
} from "../../api";
import squareFillIcon from "../images/Square_fill.svg";
import arrowDropRightIcon from "../images/Arrow_drop_right.svg";
import styles from "./styles.module.scss";

function TestSettings() {
  const { isTesting, setIsTesting } = useContext(IsTestingContext);
  const { setDataset } = useContext(datasetContext);
  const [formData, setFormData] = useState(initTestParams);
  const [datasetNameList, setDatasetNameList] = useState<string[]>([]);

  useLayoutEffect(() => {
    let ignore = false;
    getDatasetNameList().then((data) => {
      if (!ignore) setDatasetNameList(data);
    });
    return () => {
      ignore = true;
    };
  }, []);

  async function handleRun() {
    const text = await runTest(formData);
    console.log(text);
    setIsTesting(true);
  }

  async function handleStop() {
    const text = await stopTest();
    console.log(text);
    setIsTesting(false);
  }

  function handleDatasetChange(e: any) {
    setFormData((prev) => {
      return {
        ...prev,
        dataset: e.target.value,
      };
    });
    setDataset(e.target.value);
  }

  return (
    <div className={`${styles.settings} ${styles.myCard}`}>
      <h5>
        <img alt="" src={settingIcon} />
        参数设置
        <Form>
          <fieldset className={styles.subForm} disabled={isTesting}>
            <Form.Group controlId="dataset">
              <Form.Label>数据集</Form.Label>
              <Form.Select
                value={formData.dataset}
                onChange={handleDatasetChange}
              >
                {datasetNameList.map((item) => {
                  return (
                    <option key={item} value={item}>
                      {item}
                    </option>
                  );
                })}
              </Form.Select>
            </Form.Group>
          </fieldset>
        </Form>
        <div className={styles.btnsContainer}>
          <Button variant="primary" onClick={handleRun} disabled={isTesting}>
            <img alt="" src={arrowDropRightIcon}></img>
            开始
          </Button>
          <Button variant="danger" onClick={handleStop} disabled={!isTesting}>
            <img alt="" src={squareFillIcon}></img>
            停止
          </Button>
        </div>
      </h5>
    </div>
  );
}

export default TestSettings;
